package com.yunkaweilai.android.activity.member;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bilibili.boxing.Boxing;
import com.bilibili.boxing.model.entity.BaseMedia;
import com.bilibili.boxing.model.entity.impl.ImageMedia;
import com.bilibili.boxing.utils.ImageCompressor;
import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.interfaces.PopupEmployeeInterfaces;
import com.yunkaweilai.android.interfaces.StringTwoInterface;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.ImageUploadModel;
import com.yunkaweilai.android.model.MemberAlbumModel;
import com.yunkaweilai.android.model.member.MemberDiyModel;
import com.yunkaweilai.android.model.member.MemberHeadModel;
import com.yunkaweilai.android.model.member.MemberInfoModel;
import com.yunkaweilai.android.net.Glide.GlideUtils;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.ImageUtilsK;
import com.yunkaweilai.android.utils.PicturePickerHelper;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.utils.zxing.Kutils;
import com.yunkaweilai.android.view.OvalImageView;
import com.yunkaweilai.android.view.dialog.member.MemberRecommenderDialog;
import com.yunkaweilai.android.view.popup.ImageEnlageAlbumPopup;
import com.yunkaweilai.android.view.popup.ShopEmployeePopup2;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.listeners.OnSingleWheelListener;
import cn.addapp.pickers.picker.DatePicker;
import cn.addapp.pickers.picker.SinglePicker;
import okhttp3.Call;

/**
 * 修改会员信息
 * Created by Administrator on 2017/7/7.
 */

public class UpdateMemberInfoActivity extends BaseActivity implements StringTwoInterface, PopupEmployeeInterfaces {

    @BindView(R.id.id_edt_card_no)
    TextView idEdtCardNo;
    @BindView(R.id.id_edt_spare_card_no)
    TextView idEdtSpareCardNo;
    @BindView(R.id.id_tv_card_level)
    TextView idTvCardLevel;
    @BindView(R.id.id_llayout_level)
    LinearLayout idLlayoutLevel;
    @BindView(R.id.id_tv_time)
    TextView idTvTime;
    @BindView(R.id.id_llayout_time)
    LinearLayout idLlayoutTime;
    @BindView(R.id.id_img_head)
    ImageView idImgHead;
    @BindView(R.id.id_llayout_head)
    LinearLayout idLlayoutHead;
    @BindView(R.id.id_edt_name)
    EditText idEdtName;
    @BindView(R.id.id_tv_sex)
    TextView idTvSex;
    @BindView(R.id.id_llayout_sex)
    LinearLayout idLlayoutSex;
    @BindView(R.id.id_edt_tel)
    EditText idEdtTel;
    @BindView(R.id.id_tv_birthday)
    TextView idTvBirthday;
    @BindView(R.id.id_llayout_birthday)
    LinearLayout idLlayoutBirthday;
    @BindView(R.id.id_tv_anniversary_day)
    TextView idTvAnniversaryDay;
    @BindView(R.id.id_llayout_anniversary_day)
    LinearLayout idLlayoutAnniversaryDay;
    @BindView(R.id.id_llayout_diy)
    LinearLayout idLlayoutDiy;
    @BindView(R.id.id_edt_recommend_card)
    TextView idEdtRecommendCard;
    @BindView(R.id.id_tv_salesman)
    TextView idTvSalesman;
    @BindView(R.id.id_llayout_salesman)
    LinearLayout idLlayoutSalesman;
    @BindView(R.id.id_edt_remark)
    EditText idEdtRemark;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.titlebar_iv_left)
    ImageView titlebarIvLeft;
    @BindView(R.id.titlebar_tv_left)
    TextView titlebarTvLeft;
    @BindView(R.id.titlebar_tv)
    TextView titlebarTv;
    @BindView(R.id.titlebar_iv_right_2)
    ImageView titlebarIvRight2;
    @BindView(R.id.titlebar_iv_right)
    ImageView titlebarIvRight;
    @BindView(R.id.titlebar_tv_right)
    TextView titlebarTvRight;
    @BindView(R.id.id_view_underline)
    View idViewUnderline;
    @BindView(R.id.rl_titlebar)
    RelativeLayout rlTitlebar;
    @BindView(R.id.id_edt_car_no)
    EditText idEdtCarNo;
    @BindView(R.id.id_img1)
    OvalImageView idImg1;
    @BindView(R.id.id_img2)
    OvalImageView idImg2;
    @BindView(R.id.id_img3)
    OvalImageView idImg3;
    @BindView(R.id.id_img4)
    OvalImageView idImg4;
    @BindView(R.id.id_llayout_first_img)
    LinearLayout idLlayoutFirstImg;
    @BindView(R.id.id_img5)
    OvalImageView idImg5;
    @BindView(R.id.id_img6)
    OvalImageView idImg6;
    @BindView(R.id.id_llayout_next_img)
    LinearLayout idLlayoutNextImg;
    @BindView(R.id.content_view)
    ScrollView contentView;
    @BindView(R.id.id_llayout_album)
    LinearLayout idLlayoutAlbum;
    @BindView(R.id.id_view_sale)
    View idViewSale;


    private LayoutInflater inflater;
    private ArrayList<MemberDiyModel.DataBean.ListBean> diyList = new ArrayList<>();

    private boolean diyisShow = false;//是否获取到diy
    private MemberInfoModel memberInfoModel;
    //时间
    private int mYear;
    private int mMonth;
    private int mDay;
    private boolean isChangeTime = true;
    //文件路径
    private String mPicPath = "";
    private String member_avatar = "";
    private String member_sex = "male";
    private String is_sparecard_no = "0";
    private String level_id = "";
    private String member_birthday = "";
    private String member_anniversary = "";
    private Map<String, String> diymap = new HashMap<>();
    private MemberHeadModel model;
    private ArrayList<MemberAlbumModel> member_album = new ArrayList<>();
    public static final String UPDATE_MEMBER_INFO_MODEL = "UPDATE_MEMBER_INFO_MODEL";
    public static final String UPDATE_MEMBER_INFO_BUNDLE = "UPDATE_MEMBER_INFO_BUNDLE";
    private String verification_no = "";
    private String commission_id = "";

    public static void actionStart(Context context, MemberHeadModel model) {
        Intent intent = new Intent(context, UpdateMemberInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(UPDATE_MEMBER_INFO_MODEL, model);
        intent.putExtra(UPDATE_MEMBER_INFO_BUNDLE, bundle);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_member_info);
        ButterKnife.bind(this);
        model = (MemberHeadModel) getIntent().getBundleExtra(UPDATE_MEMBER_INFO_BUNDLE).getSerializable(UPDATE_MEMBER_INFO_MODEL);
        new TitleBuilder(this).setTitleText("修改会员").setLeftImage(R.mipmap.ic_go_back)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                }).setRightText("保存").setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isRight();
            }
        });
        inflater = this.getLayoutInflater();
        idMultipleStatusView.showLoading();
        initDiyHttp();
        initDate();
    }


    private void initMemberHttp() {
        HttpRequest.postUrl(Api.MEMBER_INFO_BASIC)
                .addParams("member_id", model.getId())
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean codeInfoRs = Utils.checkCode(mAc, json);
                        if (codeInfoRs) {
                            Gson gson = new Gson();
                            memberInfoModel = gson.fromJson(json, MemberInfoModel.class);
                            initView();
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showContent();
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });

    }

    //会员基本信息
    private void initView() {
        MemberHeadModel memberinfo = memberInfoModel.getData().getList();
        idLlayoutSalesman.setVisibility(View.GONE);
        idViewSale.setVisibility(View.GONE);
        member_birthday = memberinfo.getMember_birthday() + "";
        member_anniversary = memberinfo.getMember_anniversary() + "";
        member_avatar = memberinfo.getMember_avatar() + "";
        level_id = memberinfo.getLevel_id();
        idEdtCardNo.setText(memberinfo.getCard_no() + "");
        if (StringUtils.isEmpty(memberinfo.getPlate_number())) {
            idEdtCarNo.setText("");
        } else {
            idEdtCarNo.setText(memberinfo.getPlate_number() + "");
        }
        if (!StringUtils.isEmpty(memberinfo.getSparecard_no())) {
            idEdtSpareCardNo.setText(memberinfo.getSparecard_no());
        } else {
            idEdtSpareCardNo.setText("");
        }
        idTvCardLevel.setText(memberinfo.getLevel_name() + "");
        if ("1".equals(memberinfo.getIs_alwaysvalid())) {
            idTvTime.setText("永久有效");
            isChangeTime = false;
        } else {
            isChangeTime = true;
            idTvTime.setText(memberinfo.getValidtime() + "");
        }
        if ("famale".equals(memberinfo.getMember_sex())) {
            idTvSex.setText("女");
            member_sex = "famale";
        } else if ("male".equals(memberinfo.getMember_sex())) {
            idTvSex.setText("男");
            member_sex = "male";
        } else {
            idTvSex.setText("未知");
        }
        Utils.MemberHeadImg(mAc, memberinfo.getMember_avatar(), memberinfo.getMember_sex(), idImgHead);

        idEdtName.setText(memberinfo.getMember_name());
        idEdtTel.setText(memberinfo.getMember_tels() + "");
        idTvBirthday.setText(memberinfo.getMember_birthday() + "");
        idTvAnniversaryDay.setText(memberinfo.getMember_anniversary() + "");
        if (!Utils.isEmpty(memberinfo.getRecommend_name())) {
            idEdtRecommendCard.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_left));
            idEdtRecommendCard.setText(memberinfo.getRecommend_name() + "");
            verification_no = memberinfo.getRecommend_card_no();
        }
        idTvSalesman.setText(memberinfo.getCommission_name() + "");
        idEdtRemark.setText(memberinfo.getMember_remarks() + "");

        setDiyView();
        member_album = memberInfoModel.getData().getList().getMember_album();
        initAlbumView(member_album);
    }

    //会员相册
    private void initAlbumView(ArrayList<MemberAlbumModel> member_album) {
        if (member_album.size() > 0) {
            idLlayoutFirstImg.setVisibility(View.VISIBLE);
        } else {
            idLlayoutFirstImg.setVisibility(View.GONE);
        }
        if (member_album.size() > 4) {
            idLlayoutNextImg.setVisibility(View.VISIBLE);
        } else {
            idLlayoutNextImg.setVisibility(View.GONE);
        }
        switch (member_album.size()) {
            case 1:
                idImg1.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(0).getPath(), idImg1);
                idImg2.setVisibility(View.GONE);
                idImg3.setVisibility(View.GONE);
                idImg4.setVisibility(View.GONE);
                idImg5.setVisibility(View.GONE);
                idImg6.setVisibility(View.GONE);

                break;
            case 2:
                idImg1.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(0).getPath(), idImg1);
                idImg2.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(1).getPath(), idImg2);
                idImg3.setVisibility(View.GONE);
                idImg4.setVisibility(View.GONE);
                idImg5.setVisibility(View.GONE);
                idImg6.setVisibility(View.GONE);
                break;
            case 3:
                idImg1.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(0).getPath(), idImg1);
                idImg2.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(1).getPath(), idImg2);
                idImg3.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(2).getPath(), idImg3);
                idImg4.setVisibility(View.GONE);
                idImg5.setVisibility(View.GONE);
                idImg6.setVisibility(View.GONE);
                break;
            case 4:
                idImg1.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(0).getPath(), idImg1);
                idImg2.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(1).getPath(), idImg2);
                idImg3.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(2).getPath(), idImg3);
                idImg4.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(3).getPath(), idImg4);
                idImg5.setVisibility(View.GONE);
                idImg6.setVisibility(View.GONE);
                break;
            case 5:
                idImg1.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(0).getPath(), idImg1);
                idImg2.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(1).getPath(), idImg2);
                idImg3.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(2).getPath(), idImg3);
                idImg4.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(3).getPath(), idImg4);
                idImg5.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(4).getPath(), idImg5);
                idImg6.setVisibility(View.GONE);
                break;
            case 6:
                idImg1.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(0).getPath(), idImg1);
                idImg2.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(1).getPath(), idImg2);
                idImg3.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(2).getPath(), idImg3);
                idImg4.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(3).getPath(), idImg4);
                idImg5.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(4).getPath(), idImg5);
                idImg6.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(mAc, member_album.get(5).getPath(), idImg6);
                break;
        }
    }

    //对会员存在的自定义属性进行设置
    private void setDiyView() {
        List<MemberInfoModel.DataBean.DiyfieldListBean> diyfield_list = memberInfoModel.getData().getDiyfield_list();
        for (int i = 0; i < diyfield_list.size(); i++) {
            MemberInfoModel.DataBean.DiyfieldListBean diyfieldListBean = diyfield_list.get(i);
            for (int j = 0; j < diyList.size(); j++) {
                if (diyList.get(j).getId().equals(diyfieldListBean.getId())) {
                    View childAt = idLlayoutDiy.getChildAt(j);
                    ((TextView) childAt.findViewById(R.id.id_tv_name)).setText(diyfieldListBean.getField_name());
                    if ("text".equals(diyfieldListBean.getField_type())) {
                        ((EditText) childAt.findViewById(R.id.id_edt_content)).setText(diyfieldListBean.getDiyfield_contents());
                    } else {
                        TextView viewById = (TextView) childAt.findViewById(R.id.id_tv_content);
                        viewById.setText(diyfieldListBean.getDiyfield_contents());
                        viewById.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_left));
                    }
                }
            }
        }
    }


    //验证参数是否完全
    private void isRight() {
        if (StringUtils.isEmpty(level_id)) {
            showToast("还未选择卡等级");
            return;
        }
        if (StringUtils.isEmpty(idTvTime.getText().toString())) {
            showToast("还未选择有效期");
            return;
        }
        if (!StringUtils.isEmpty("") && !(idEdtTel.getText().toString().length() == 11)) {
            showToast("请填写正确的手机号");
            return;
        }

        showProgressDialog("请稍等，正在保存信息");
        initAddMember();
        //保存会员
    }

    //修改会员接口
    private void initAddMember() {
        PostProcess postProcess = HttpRequest.postUrl(Api.ADD_MEMBER_INFO)
                .addParams("id", model.getId())
                .addParams("card_no", idEdtCardNo.getText().toString())
                .addParams("is_sparecard_no", is_sparecard_no)
                .addParams("sparecard_no", idEdtSpareCardNo.getText().toString())
                .addParams("level_id", level_id)
                .addParams("member_name", idEdtName.getText().toString() + "")
                .addParams("member_sex", member_sex)
                .addParams("member_tel", idEdtTel.getText().toString() + "")
                .addParams("member_birthday_type", "gong")
                .addParams("member_birthday", member_birthday)
                .addParams("member_remarks", idEdtRemark.getText().toString())
                .addParams("member_anniversary", member_anniversary)
                .addParams("member_avatar", member_avatar)
                .addParams("is_alwaysvalid", isChangeTime ? "0" : "1")
                .addParams("validtime", idTvTime.getText().toString())
                .addParams("edit_type", "Edit")
                .addParams("recommend_card_no", verification_no + "")
                .addParams("plate_number", idEdtCarNo.getText().toString() + "");

        Iterator iter = diymap.entrySet().iterator();//自定义字段
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            String val = (String) entry.getValue();
            postProcess.addParams(key, val);
        }
        for (int i = 0; i < member_album.size(); i++) {
            MemberAlbumModel memberAlbumModel = member_album.get(i);
            postProcess.addParams("albumList[" + i + "][path]", memberAlbumModel.getPath());
            postProcess.addParams("albumList[" + i + "][id]", memberAlbumModel.getId() + "");
            postProcess.addParams("albumList[" + i + "][album_remark]", memberAlbumModel.getAlbum_remark());
        }
        postProcess.execute(new PostProcess.StringCallBack() {
            @Override
            public void onResponse(String json) {
                boolean checkCode = Utils.checkCode(mAc, json);
                if (checkCode) {
                    model.setCard_no(idEdtCardNo.getText().toString() + "");
                    model.setMember_avatar(member_avatar);
                    model.setMember_name(idEdtName.getText().toString());
                    model.setLevel_name(idTvCardLevel.getText().toString());
                    EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.MEMBER_LIST, true));
                    EventBus.getDefault().post(new Event.OtherTypeEvent(CommonConstants.MEMBER_INFO_LIST, true, model));
                    EventBus.getDefault().post(new Event.OtherTypeEvent(CommonConstants.LOCK_REFRESH, true, model));
                    mAc.finish();
                }
                dismissProgressDialog();
                showLog(json);
            }

            @Override
            public void onError(Exception e) {
                showToast("系统错误");
                dismissProgressDialog();
            }
        });

    }

    private void initDate() {
        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        mYear = c.get(Calendar.YEAR);// 获取当前年份
        mMonth = c.get(Calendar.MONTH) + 1;// 获取当前月份
        mDay = c.get(Calendar.DAY_OF_MONTH);// 获取当前月份的日期号码
    }

    private void initDiyHttp() {
        HttpRequest.postUrl(Api.ADD_MEMBER_CUSTOM_ATTRIBUTES)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        diyisShow = Utils.checkCode(mAc, json);
                        if (diyisShow) {
                            initAddView(json);
                        }
                        initMemberHttp();
                    }

                    @Override
                    public void onError(Exception e) {
                        diyisShow = false;
                        initMemberHttp();
                    }
                });
    }

    private void initAddView(String json) {
        Gson gson = new Gson();
        MemberDiyModel memberDiyModel = gson.fromJson(json, MemberDiyModel.class);
        diyList.clear();
        diyList.addAll(memberDiyModel.getData().getList());
        for (int i = 0; i < diyList.size(); i++) {
            MemberDiyModel.DataBean.ListBean listBean = diyList.get(i);
            LinearLayout view = null;
            if ("text".equals(listBean.getField_type())) {
                view = (LinearLayout) inflater
                        .inflate(R.layout.view_member_diy_edt, null);
                diyEdts(i, view);
            } else if ("select_time".equals(listBean.getField_type())) {
                view = (LinearLayout) inflater
                        .inflate(R.layout.view_member_diy_txt, null);
                diyTimes(i, view);
            } else if ("radio".equals(listBean.getField_type())) {
                view = (LinearLayout) inflater
                        .inflate(R.layout.view_member_diy_txt, null);
                diyRadio(i, view);
            } else if ("checkbox".equals(listBean.getField_type())) {
                view = (LinearLayout) inflater
                        .inflate(R.layout.view_member_diy_txt, null);
                diyCheck(i, view);
            }
            idLlayoutDiy.addView(view);
        }

    }

    private void diyCheck(int position, LinearLayout view) {
        ((TextView) view.findViewById(R.id.id_tv_name)).setText(diyList.get(position).getField_name());
        final TextView idTvContent = (TextView) view.findViewById(R.id.id_tv_content);
        idTvContent.setTag(position);
        idTvContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int tag = (int) v.getTag();
                checkboxSelector(diyList.get(tag).getField_content(), tag);
            }
        });
    }

    //diy单选
    private void diyRadio(final int position, LinearLayout view) {
        ((TextView) view.findViewById(R.id.id_tv_name)).setText(diyList.get(position).getField_name());
        final TextView idTvContent = (TextView) view.findViewById(R.id.id_tv_content);
        idTvContent.setTag(position);
        idTvContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int tag = (int) v.getTag();
                initPickerSingle(diyList.get(tag).getField_content(), tag);
            }
        });
    }

    //diy时间选择
    private void diyTimes(int position, LinearLayout view) {
        ((TextView) view.findViewById(R.id.id_tv_name)).setText(diyList.get(position).getField_name());
        final TextView idTvContent = (TextView) view.findViewById(R.id.id_tv_content);
        idTvContent.setTag(position);
        idTvContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                initDate();
                final int tag = (int) v.getTag();
                final LinearLayout childAt = (LinearLayout) idLlayoutDiy.getChildAt(tag);
                final TextView viewById = (TextView) childAt.findViewById(R.id.id_tv_content);
                final String s = viewById.getText().toString();
                if (s.contains("-")) {
                    String[] all = s.split("-");
                    mYear = Integer.parseInt(all[0]);
                    mMonth = Integer.parseInt(all[1]);
                    mDay = Integer.parseInt(all[2]);
                }

                final DatePicker picker = new DatePicker(mAc);
                picker.setCanLoop(false);
                picker.setWheelModeEnable(true);
                picker.setTopPadding(15);
                picker.setRangeStart(1930, 1, 01);
                picker.setRangeEnd(mYear + 100, 11, 11);
                picker.setSelectedItem(mYear, mMonth, mDay);
                picker.setWeightEnable(true);
                picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        viewById.setText(year + "-" + month + "-" + day);
                        viewById.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_left));
                        diymap.put("member_otherfield[" + diyList.get(tag).getId() + "]", year + "-" + month + "-" + day);
                    }
                });
                picker.setOnWheelListener(new DatePicker.OnWheelListener() {
                    @Override
                    public void onYearWheeled(int index, String year) {
                        picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
                    }

                    @Override
                    public void onMonthWheeled(int index, String month) {
                        picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
                    }

                    @Override
                    public void onDayWheeled(int index, String day) {
                        picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
                    }
                });
                picker.show();
            }
        });
    }

    //处理diy文本信息
    private void diyEdts(final int position, LinearLayout view) {
        ((TextView) view.findViewById(R.id.id_tv_name)).setText(diyList.get(position).getField_name());
        EditText edtContent = (EditText) view.findViewById(R.id.id_edt_content);
        edtContent.setTag(position);
        edtContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                diymap.put("member_otherfield[" + diyList.get(position).getId() + "]", s.toString() + "");
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                switch (requestCode) {
                    case 302://有效期
                        String level_name = data.getStringExtra(AddMemberInfoActivity.MEMBER_LEVEL_NAME);
                        String level_time_type = data.getStringExtra(AddMemberInfoActivity.MEMBER_LEVEL_VALIDITY_TYPE);
                        long level_time = data.getLongExtra(AddMemberInfoActivity.MEMBER_LEVEL_VALIDITY, 0);
                        level_id = data.getStringExtra(AddMemberInfoActivity.MEMBER_LEVEL_ID);
                        idTvCardLevel.setText(level_name);
                        String times = "";
                        switch (level_time_type) {
                            case "permanent":
                                times = "永久有效";
                                isChangeTime = false;
                                break;
                            case "appoint"://指定时间
                                times = Kutils.getDay(level_time);
                                isChangeTime = true;
                                break;
                            case "year":
                                mYear = (int) (mYear + level_time);
                                times = mYear + "-" + mMonth + "-" + mDay;
                                isChangeTime = true;
                                break;
                            case "month":
                                mMonth = (int) (mMonth + level_time);
                                times = mYear + "-" + mMonth + "-" + mDay;
                                isChangeTime = true;
                                break;
                            case "day":
                                mDay = (int) (mDay + level_time);
                                if (mDay > Utils.MaxDayFromDay_OF_MONTH(mYear, mMonth)) {
                                    mDay = Utils.MaxDayFromDay_OF_MONTH(mYear, mMonth);
                                    mMonth++;
                                }
                                times = mYear + "-" + mMonth + "-" + mDay;
                                isChangeTime = true;
                                break;
                            default:
                                isChangeTime = true;
                                break;
                        }
                        idTvTime.setText(times);
                        break;
                    case 303://头像
                        final ArrayList<BaseMedia> medias = Boxing.getResult(data);
                        BaseMedia baseMedia = medias.get(0);
                        if (!(baseMedia instanceof ImageMedia)) {
                            return;
                        }
                        showProgressDialog("请稍等，图片上传中...");
                        final ImageMedia imageMedia = (ImageMedia) baseMedia;
                        //对返回的图片进行压缩
                        if (imageMedia.compress(new ImageCompressor(this))) {
                            imageMedia.removeExif();
                        }
                        //压缩质量和尺寸 上面这个不靠谱
                        File fileDir = Environment.getExternalStorageDirectory();
                        BitmapFactory.Options opts = new BitmapFactory.Options();
                        Bitmap bitmap = BitmapFactory.decodeFile(imageMedia.getPath(), opts);// 文件路径
                        ImageUtilsK.compressImage2File(bitmap, new File(fileDir, "updateMember.jpg"));
                        File file1 = new File(fileDir, "updateMember.jpg");
                        mPicPath = file1.getAbsolutePath();
//                        mPicPath = imageMedia.getPath();
                        uploadFile(mPicPath);
                        break;
                    case 304://业务员
                        String name = data.getStringExtra(MemberRechargeActivity.PERCENTAGES_STAFF_NAME);
                        commission_id = data.getStringExtra(MemberRechargeActivity.PERCENTAGES_STAFF_ID);
                        idTvSalesman.setText(name + "");
                        break;
                    case 305://相册
                        member_album = (ArrayList<MemberAlbumModel>) data.getSerializableExtra(MemberAlbumActivity.ALBUM_LIST);
                        if (member_album == null) {
                            member_album = new ArrayList<>();
                        }
                        initAlbumView(member_album);
                        break;
                    case PictureConfig.CHOOSE_REQUEST:
                        String uri = PicturePickerHelper.onPickLogoOrAvatarActivityResult(requestCode, resultCode, data);
                        if (!StringUtils.isEmpty(uri)) {
                            uploadFile(uri);
                        } else {
                            showToast("未选择照片");
                        }
                        break;
                }
            }

        }
    }

    public int MEMBER_LEVEL = 302;//会员级别
    public int MEMBER_HEAD_IMAGE = 303;//会员头像
    public int MEMBER_COMMISIONG_PEOPLE = 304;//业务员
    public int MEMBER_ALBUM_LIST = 305;//会员相册

    @OnClick({R.id.id_edt_recommend_card, R.id.id_llayout_album, R.id.id_llayout_level, R.id.id_llayout_time, R.id.id_llayout_head, R.id.id_llayout_sex, R.id.id_llayout_birthday, R.id.id_llayout_anniversary_day, R.id.id_llayout_salesman
            , R.id.id_img1, R.id.id_img2, R.id.id_img3, R.id.id_img4, R.id.id_img5, R.id.id_img6})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.id_edt_recommend_card:
                MemberRecommenderDialog dialog = new MemberRecommenderDialog(mAc, this);
                dialog.show();
                break;
            case R.id.id_llayout_album:
                intent = new Intent(mAc, MemberAlbumActivity.class);
                intent.putExtra(MemberAlbumActivity.ALBUM_LIST_GET_LIST, (Serializable) member_album);
                startActivityForResult(intent, MEMBER_ALBUM_LIST);
                break;
            case R.id.id_llayout_level://级别
                startActivityForResult(new Intent(mAc, MemberLevelActivity.class), MEMBER_LEVEL);
                break;
            case R.id.id_llayout_time://有效期
                ArrayList<String> timelist = new ArrayList<>();
                timelist.add("永久有效");
                timelist.add("选择有效期");
                initTimeOrCard(timelist);
                break;
            case R.id.id_llayout_head://头像
//                String cachePath = BoxingFileHelper.getCacheDir(this);
//                if (TextUtils.isEmpty(cachePath)) {
//                    Toast.makeText(this, R.string.storage_deny, Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                Uri destUri = new Uri.Builder()
//                        .scheme("file")
//                        .appendPath(cachePath)
//                        .appendPath(String.format(Locale.US, "%s.jpg", System.currentTimeMillis()))
//                        .build();
//                BoxingConfig singleCropImgConfig = new BoxingConfig(BoxingConfig.Mode.SINGLE_IMG).withCropOption(new BoxingCropOption(destUri).aspectRatio(1, 1)).needCamera();
//                Boxing.of(singleCropImgConfig).withIntent(this, PhotoPickerActivity.class).start(this, MEMBER_HEAD_IMAGE);
                PicturePickerHelper.pickLogoOrAvatar(UpdateMemberInfoActivity.this);
                break;
            case R.id.id_llayout_sex://性别
                ArrayList<String> list = new ArrayList<>();
                list.add("男");
                list.add("女");
                pickerSelSex(list);
                break;
            case R.id.id_llayout_birthday://生日
                idTvBirthday.setTag("birthday");
                initPickerData2(idTvBirthday);
                break;
            case R.id.id_llayout_anniversary_day://纪念日
                idTvAnniversaryDay.setTag("anniversary");
                initPickerData2(idTvAnniversaryDay);
                break;
            case R.id.id_llayout_salesman://操作人

                ShopEmployeePopup2 shopPopup = new ShopEmployeePopup2(mAc, employeeStr, Api.PERCENTAGES_FOR_CONSUME);
                shopPopup.setInterface(UpdateMemberInfoActivity.this);
                shopPopup.showPopupWindow();
                break;
            case R.id.id_img1:
                if (member_album.size() > 0) {
                    ImageEnlageAlbumPopup popup = new ImageEnlageAlbumPopup(mAc, member_album.get(0).getPath(), R.mipmap.ic_image_add, member_album.get(0).getAlbum_remark());
                    popup.showPopupWindow();
                }
                break;
            case R.id.id_img2:
                if (member_album.size() > 1) {
                    ImageEnlageAlbumPopup popup = new ImageEnlageAlbumPopup(mAc, member_album.get(1).getPath(), R.mipmap.ic_image_add, member_album.get(1).getAlbum_remark());
                    popup.showPopupWindow();
                }
                break;
            case R.id.id_img3:
                if (member_album.size() > 2) {
                    ImageEnlageAlbumPopup popup = new ImageEnlageAlbumPopup(mAc, member_album.get(2).getPath(), R.mipmap.ic_image_add, member_album.get(2).getAlbum_remark());
                    popup.showPopupWindow();
                }
                break;
            case R.id.id_img4:
                if (member_album.size() > 3) {
                    ImageEnlageAlbumPopup popup = new ImageEnlageAlbumPopup(mAc, member_album.get(3).getPath(), R.mipmap.ic_image_add, member_album.get(3).getAlbum_remark());
                    popup.showPopupWindow();
                }
                break;
            case R.id.id_img5:
                if (member_album.size() > 4) {
                    ImageEnlageAlbumPopup popup = new ImageEnlageAlbumPopup(mAc, member_album.get(4).getPath(), R.mipmap.ic_image_add, member_album.get(4).getAlbum_remark());
                    popup.showPopupWindow();
                }
                break;
            case R.id.id_img6:
                if (member_album.size() > 5) {
                    ImageEnlageAlbumPopup popup = new ImageEnlageAlbumPopup(mAc, member_album.get(5).getPath(), R.mipmap.ic_image_add, member_album.get(5).getAlbum_remark());
                    popup.showPopupWindow();
                }
                break;
        }
    }

    private String employeeStr = "";

    //时间选择
    private void initPickerData(final TextView tvView) {
        initDate();
        String s = tvView.getText().toString();
        if (s.contains("-")) {
            String[] all = s.split("-");
            mYear = Integer.parseInt(all[0]);
            mMonth = Integer.parseInt(all[1]);
            mDay = Integer.parseInt(all[2]);
        }
        final DatePicker picker = new DatePicker(this);
        picker.setCanLoop(false);
        picker.setWheelModeEnable(true);
        picker.setTopPadding(15);
        picker.setRangeStart(mYear - 70, 1, 01);
        picker.setRangeEnd(mYear + 70, 11, 11);
        picker.setSelectedItem(mYear, mMonth, mDay);
        picker.setWeightEnable(true);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                String tag = (String) tvView.getTag();
                if ("times".equals(tag + "")) {
                    isChangeTime = true;
                }
                if ("birthday".equals(tag + "")) {
                    member_birthday = year + "-" + month + "-" + day;
                }
                if ("anniversary".equals(tag + "")) {
                    member_anniversary = year + "-" + month + "-" + day;
                }
                tvView.setText(year + "-" + month + "-" + day);
            }
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        picker.show();
    }

    //时间选择
    private void initPickerData2(final TextView tvView) {
        initDate();
        String s = tvView.getText().toString();
        if (s.contains("-")) {
            String[] all = s.split("-");
            mMonth = Integer.parseInt(all[0]);
            mDay = Integer.parseInt(all[1]);
        }
        final DatePicker picker = new DatePicker(mAc, DatePicker.MONTH_DAY);
        picker.setCanLoop(false);
        picker.setWheelModeEnable(true);
        picker.setTopPadding(15);
        picker.setRangeStart(1, 01);
        picker.setRangeEnd(12, 31);
        picker.setSelectedItem(mMonth, mDay);
        picker.setWeightEnable(true);
        picker.setOnDatePickListener(new DatePicker.OnMonthDayPickListener() {
            @Override
            public void onDatePicked(String month, String day) {
                String tag = (String) tvView.getTag();
                if ("times".equals(tag + "")) {
                    isChangeTime = true;
                }
                if ("birthday".equals(tag + "")) {
                    member_birthday = month + "-" + day;
                }
                if ("anniversary".equals(tag + "")) {
                    member_anniversary = month + "-" + day;
                }
                tvView.setText(month + "-" + day);
                tvView.setTextColor(getResources().getColor(R.color.wjx_content_txt));
            }
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedMonth() + "-" + day);
            }
        });
        picker.show();
    }


    //文件上传
    private void uploadFile(final String mPicPath) {
        Map<String, String> paprms = new HashMap<>();
        paprms.put("token", BaseApplication.getToken());
        OkHttpUtils.post().addFile("file", "shop.jpg", new File(mPicPath))
                .url(Api.IMAGE_UPLOAD).params(paprms).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        showToast("上传失败");
                    }
                });
            }

            @Override
            public void onResponse(final String response, int id) {
                boolean isChecked = Utils.checkCode(mAc, response);
                final Gson gson = new Gson();
                if (!isChecked) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissProgressDialog();
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissProgressDialog();
                            ImageUploadModel imageUploadModel = gson.fromJson(response, ImageUploadModel.class);
                            member_avatar = imageUploadModel.getData().getPath();
                            GlideUtils.loadCircleImage(mAc, member_avatar, idImgHead);
                            PictureFileUtils.deleteCacheDirFile(UpdateMemberInfoActivity.this);
                        }
                    });
                }
            }
        });
    }

    //性别选择
    private void pickerSelSex(List<String> list) {
        SinglePicker<String> picker = new SinglePicker<>(this, list);
        picker.setCanLoop(false);//不禁用循环
        picker.setLineVisible(true);
        picker.setShadowVisible(true);
        picker.setTextSize(18);
        picker.setSelectedIndex(0);
        picker.setWheelModeEnable(true);
        //启用权重 setWeightWidth 才起作用
        picker.setWeightEnable(true);
        picker.setWeightWidth(1);
        picker.setSelectedTextColor(0xFF279BAA);//前四位值是透明度
        picker.setUnSelectedTextColor(0xFF999999);
        picker.setOnSingleWheelListener(new OnSingleWheelListener() {
            @Override
            public void onWheeled(int index, String item) {

            }
        });
        picker.setOnItemPickListener(new OnItemPickListener<String>() {
            @Override
            public void onItemPicked(int index, String item) {
                idTvSex.setText(item);
                if (index == 0) {
                    member_sex = "male";
                } else if (index == 1) {
                    member_sex = "famale";
                }

            }
        });
        picker.show();
    }

    //单选处理
    private void initPickerSingle(List<String> list, final int position) {
        SinglePicker<String> picker = new SinglePicker<>(this, list);
        picker.setCanLoop(false);//不禁用循环
        picker.setLineVisible(true);
        picker.setShadowVisible(true);
        picker.setTextSize(18);
        picker.setSelectedIndex(0);
        picker.setWheelModeEnable(true);
        //启用权重 setWeightWidth 才起作用
        picker.setWeightEnable(true);
        picker.setWeightWidth(1);
        picker.setSelectedTextColor(0xFF279BAA);//前四位值是透明度
        picker.setUnSelectedTextColor(0xFF999999);
        picker.setOnSingleWheelListener(new OnSingleWheelListener() {
            @Override
            public void onWheeled(int index, String item) {


            }
        });
        picker.setOnItemPickListener(new OnItemPickListener<String>() {
            @Override
            public void onItemPicked(int index, String item) {
                LinearLayout childAt = (LinearLayout) idLlayoutDiy.getChildAt(position);
                TextView viewById = (TextView) childAt.findViewById(R.id.id_tv_content);
                viewById.setText(item);
                viewById.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_left));
                diymap.put("member_otherfield[" + diyList.get(position).getId() + "]", item);
            }
        });
        picker.show();
    }

    //处理多选
    private void checkboxSelector(final ArrayList<String> list, final int position) {
        new MaterialDialog.Builder(this)
                .items(list)
                .itemsCallbackMultiChoice(
                        new Integer[]{}, new MaterialDialog.ListCallbackMultiChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog dialog, Integer[] which, CharSequence[] text) {
                                return true;
                            }
                        })
                .positiveText("确定")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        Integer[] selectedIndices = dialog.getSelectedIndices();
                        String selector = "";
                        for (int i = 0; i < selectedIndices.length; i++) {
                            if (i != 0) {
                                selector = selector + ",";
                            }
                            selector = selector + list.get(selectedIndices[i]);
                        }
                        LinearLayout childAt = (LinearLayout) idLlayoutDiy.getChildAt(position);
                        TextView viewById = (TextView) childAt.findViewById(R.id.id_tv_content);
                        viewById.setText(selector);
                        viewById.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_left));
                        String s = diymap.get("member_otherfield[" + diyList.get(position).getId() + "]");
                        if ("".equals(s)) {
                        } else {
                            diymap.remove("member_otherfield[" + diyList.get(position).getId() + "]");
                        }
                        diymap.put("member_otherfield[" + diyList.get(position).getId() + "]", selector);
                    }
                })
                .neutralText("取消")
                .onNeutral(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                })
                .alwaysCallMultiChoiceCallback() // the callback will always be called, to check if (un)selection is still allowed
                .show();
    }

    //选择推荐人
    @Override
    public void getString(String verification_no, String name) {
        this.verification_no = verification_no + "";
        idEdtRecommendCard.setText(name + "");
        idEdtRecommendCard.setTextColor(getResources().getColor(R.color.wjx_content_txt));
    }


    //为了有效期单独开放
    private void initTimeOrCard(List<String> list) {
        SinglePicker<String> picker = new SinglePicker<>(this, list);
        picker.setCanLoop(false);//不禁用循环
        picker.setLineVisible(true);
        picker.setShadowVisible(true);
        picker.setTextSize(18);
        picker.setSelectedIndex(0);
        picker.setWheelModeEnable(true);
        //启用权重 setWeightWidth 才起作用
        picker.setWeightEnable(true);
        picker.setWeightWidth(1);
        picker.setSelectedTextColor(0xFF279BAA);//前四位值是透明度
        picker.setUnSelectedTextColor(0xFF999999);
        picker.setOnSingleWheelListener(new OnSingleWheelListener() {
            @Override
            public void onWheeled(int index, String item) {


            }
        });
        picker.setOnItemPickListener(new OnItemPickListener<String>() {
            @Override
            public void onItemPicked(int index, String item) {
                if ("选择有效期".equals(item)) {
                    idTvTime.setTag("times");
                    initPickerData(idTvTime);
                } else {
                    idTvTime.setText(item + "");
                    isChangeTime = false;
                }
            }
        });
        picker.show();
    }

    @Override
    public void refresh(String empName, String empStr) {
        idTvSalesman.setText(empName + "");
        employeeStr = empStr;
    }
}
